import {defineStore} from 'pinia'
import {getUserInfoLocal, removeToken, setToken, setUserInfoLocal} from "@/libs/util.js";
import localRouters from "@/router/routers.js";
import {getRoutesByUserId} from "@/module-base/api/sysManage.js";
import Main from "@/components/main/index.js";
import parentView from "@/components/parent-view/index.js";
import router from "@/router";

export const useLoginStore = defineStore('login', {
    state: () => ({
        hasGetInfo: false,
        token: '',
        userInfo: {},
        routers: [],
        hasRouter: false,
    }),
    actions: {
        /**
         * 登录时维护全局变量
         * @param loginRs 登录成功后的返回值
         * @param loginRs.accessToken token
         * @param loginRs.refreshTokenId refreshTokenId
         * @param loginRs.data 用户信息*/
        async handleLogIn(loginRs) {
            // debugger
            const {accessToken, refreshTokenId, data} = loginRs
            console.log('userInfo', data)
            setToken(accessToken, refreshTokenId)
            this.token = accessToken
            // 维护全局用户信息
            this.userInfo = data
            setUserInfoLocal(data)
            //     维护路由信息
            await this.setRouters()
        },
        /**
         * 退出登录*/
        handleLogOut() {
            removeToken()
            localStorage.clear()
            sessionStorage.clear()
        },
        // 获取路由
        async setRouters() {
            let routesData=sessionStorage.getItem('routesData')
            if(!routesData){
                // 远端获取路由列表
                routesData = (await getRoutesByUserId(this.userInfo.id)).data
                // 缓存路由
                sessionStorage.setItem('routesData', JSON.stringify(routesData))
            }
            // routesData = await getRoutesByUserId(this.userInfo.id)

            // 根据远端返回的路由列表，格式化权限路由
            const accessRoutes = _filterAsyncRouter(routesData)
            // 合并本地和远端路由，获取完整路由
            let fullRoutes = localRouters.concat(accessRoutes)
            // 格式化路由图标，TODO:后续完善
            fullRoutes = _getTagIcon(fullRoutes)
            // 全局状态管理路由
            this.routers = filterRoutes(fullRoutes)
            accessRoutes.forEach(item => {
                router.addRoute(item)
                // console.log("遍历添加动态路由")
            })
            // console.log(router.getRoutes())
            this.setHasRouter(true)
        },
        // 设置是否有路由
        setHasRouter(value) {
            this.hasRouter = value
        },
        // 获取全部路由
        getRouters() {
            debugger
            return this.routers
        }
    }
})


/**
 * 格式化路由列表*/
function _filterAsyncRouter(asyncRouterMap) {
    if(typeof asyncRouterMap==='string'){
        asyncRouterMap=JSON.parse(asyncRouterMap)
    }
    return asyncRouterMap.filter((route) => {
        if (route.component) {
            // Layout组件特殊处理
            if (route.component === 'Main') {
                route.component = Main
            } else if (route.component === 'parentView') {
                route.component = parentView
            } else {
                route.component = loadView(route.component)
            }
        }
        route.meta.notCache = route.notCache ? true : false

        if (route.children != null && route.children && route.children.length) {
            route.children = _filterAsyncRouter(route.children)
        }
        return true
    })
}

//维护路由图标
function _getTagIcon(routerTree) {
    routerTree.forEach(rt => {
        let rtIcon = rt.meta.icon ? rt.meta.icon : "custom-star"
        rt.meta.tagIcon = rtIcon
        _checkCustomIcon(rt)
        if (rt.children && rt.children.length) {
            rt.children.forEach(child => {
                child.meta.tagIcon = rtIcon
                _checkCustomIcon(child)
            })
        }
    })
    return routerTree
}

const _checkCustomIcon = (rt) => {
    let custom = rt.meta.tagIcon.indexOf("custom") > -1 ? true : false
    rt.meta.customTagIcon = custom

}
// 递归处理路由数组，移除包含 hideInMenu: true 的元素
function filterRoutes(routes) {
    // 过滤当前层级的路由，排除 hideInMenu 为 true 的项
    return routes
        .filter(route => !route.meta?.hideInMenu)
        .map(route => {
            // 如果当前路由有子路由，递归处理子路由
            if (route.children && route.children.length > 0) {
                return {
                    ...route,
                    children: filterRoutes(route.children) // 递归过滤子路由
                };
            }
            return route; // 无 children 则直接返回
        });
}